package com.evan.common.connection;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.evan.common.connection.remotefile.RemoteImageDownloader;

public class Net {

//	private DefaultHttpClient httpClient;
	private boolean isStop = false;

	public final static int PROGRESS_TOTALSIZE = 0x100,
			PROGRESS_PROCESS = 0x200, PROGRESS_FINISH = 0x300,
			FILE_EXCEPTION = 0x400;

	/**
	 * 资源下载
	 * 
	 * @param context
	 *            上下文对象
	 * @param url
	 *            下载url地址
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public byte[] downloadResource(String url) throws ClientProtocolException,
			IOException {
		ByteArrayBuffer buffer = null;
		InputStream inputstream = null;
		try {
			URL myURL = new URL(url);
			URLConnection conn = myURL.openConnection();

			conn.connect();
			inputstream = conn.getInputStream();
			if (inputstream != null) {
				buffer = new ByteArrayBuffer(1024);
				byte[] tmp = new byte[1024];
				int len;
				while (((len = inputstream.read(tmp)) != -1)
						&& (false == isStop)) {
					buffer.append(tmp, 0, len);
				}
			}

			return buffer.toByteArray();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (inputstream != null) {
				inputstream.close();
				inputstream = null;
			}
			buffer = null;
		}
		return null;
	}

//	/**
//	 * 强制关闭请求
//	 * 
//	 * @throws IOException
//	 */
//	public synchronized void cancel() throws IOException {
//		if (null != httpClient) {
//			isStop = true;
//			httpClient.getConnectionManager().shutdown();
//			httpClient = null;
//		}
//		if (inputstream != null) {
//			inputstream.close();
//		}
//	}

	/**
	 * 判断接入点类型
	 * 
	 * @return
	 */
	public static String isNetType(Context context) {
		String nettype = null;
		if (context == null) {
			return null;
		}
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mobNetInfo = connectivityManager.getActiveNetworkInfo();
		if (mobNetInfo != null) {
			if (mobNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				nettype = mobNetInfo.getTypeName(); // 当前联网类型是WIFI
			} else {
				nettype = mobNetInfo.getExtraInfo();// 当前联网类型是cmnet/cmwap
			}
		}

		return nettype;
	}

	/**
	 * @param context
	 * @param path
	 * @param handler
	 *            download form web server
	 */
	public static void doDownloadTheFile(final Context context,
			final String path, final Handler handler, final String dir) {
		new Thread() {
			@Override
			public void run() {
				String fileName = RemoteImageDownloader.getFileNameString(path,
						false);
				InputStream is = null;
				FileOutputStream fos = null;
				try {
					URL myURL = new URL(path);
					URLConnection conn = myURL.openConnection();
					conn.connect();
					is = conn.getInputStream();
					Message msg = Message.obtain();
					msg.what = PROGRESS_TOTALSIZE;
					msg.arg1 = conn.getContentLength();
					handler.sendMessage(msg);
					if (is == null) {
						return;
					}
					File myTempFile = new File(
							Environment.getExternalStorageDirectory() + dir);
					if (!myTempFile.isDirectory())
						myTempFile.mkdirs();
					if (fileName.indexOf(".apk") != -1) {
						fileName = fileName.substring(0,
								fileName.indexOf(".apk") + ".apk".length());
					}
					File apkFile = new File(myTempFile.getAbsolutePath() + "/"
							+ fileName);
					if (!apkFile.exists()) {
						apkFile.createNewFile();
					}
					String currentTempFilePath = apkFile.getAbsolutePath();
					boolean fileflag = false;
					try {
						fos = new FileOutputStream(apkFile);
						fileflag = true;
					} catch (FileNotFoundException e) {
						e.printStackTrace();
						fileflag = false;
					}
					if (fileflag) {
						byte buf[] = new byte[128];
						int numread = 0;
						int process = 0;
						int count = conn.getContentLength() / 1024 / 100;
						while ((numread = is.read(buf)) > 0) {
							fos.write(buf, 0, numread);
							count++;
							process += numread;
							if (count == 100) {
								Message message = Message.obtain();
								message.what = PROGRESS_PROCESS;
								message.arg1 = process;
								handler.sendMessage(message);
								count = 0;
							}
						}
						buf = null;
						Message finishMsg = Message.obtain();
						finishMsg.what = PROGRESS_FINISH;
						finishMsg.obj = currentTempFilePath;
						handler.sendMessage(finishMsg);
						
						conn = null;
						myTempFile = null;
						return;
					} else {
						handler.sendEmptyMessage(FILE_EXCEPTION);
						return;
					}
				} catch (Exception e) {
					e.printStackTrace();
					return;
				} finally {
					try {
						if (is != null)
							is.close();
						if (fos != null)
							fos.close();
					} catch (Exception ex) {
					}
				}
			}

		}.start();
	}
}
